package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import model.Article;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @description: 博客正文
 * @author: chengbaiyi
 * @create: 2022-05-20 21:17
 */
@WebServlet("/artdetail")
public class ArtDetailServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Article article = new Article();
        String msg = "未知错误";
        // 1.得到前端的参数并校验
        String aidStr = req.getParameter("aid");
        if (!StrUtil.isBlank(aidStr)) {
            // 2.查询数据库获取文章详情
            Connection connection = DBUtils.getConnection();
            String sql = "select * from article where aid=?";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setInt(1, Integer.parseInt(aidStr));
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                article.setAid(resultSet.getInt("aid"));
                article.setTitle(resultSet.getString("title"));
                article.setContext(resultSet.getString("context"));
                String create_time = resultSet.getString("create_time");
                article.setCreate_time(create_time.substring(0, create_time.lastIndexOf(".")));
                article.setRead_count(resultSet.getInt("read_count"));
            }
            msg = "";
            DBUtils.close(resultSet, statement, connection);
        } else {
            msg = "参数错误！";
        }
        // 3.将结果返回给前端
        resp.setContentType(AppVar.RESPONSE_CONTENTTYPE_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200, article, msg)));
    }
}
